package thread;

// 此处不考虑泛型参数, 只是基于 String 进行存储.
class MyBlockingQueue {
    private String[] data = null;
    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;

    private Object locker = new Object();

    public MyBlockingQueue(int capacity) {
        data = new String[capacity];
    }

    public void put(String s) throws InterruptedException {
        // 加锁的对象, 可以单独定义一个, 也可以直接就地使用 this.
        synchronized (this) {
            //while的作用就是在wait被唤醒之后,再次确认条件,看是否能继续执行
            while (size == data.length) {
                // 队列满了
                // return;
                this.wait();
            }
            data[tail] = s;
            tail++;
            if (tail >= data.length) {
                tail = 0;
            }
            size++;

            this.notify();
        }
    }

    public String take() throws InterruptedException{
        String ret = "";
        synchronized (this) {
            //这里用while而不是if
            while (size == 0) {
                // 队列为空
                // return null;
                //如果是try-catch,用if还是while的话问题就很大,wait被唤醒就会继续往下执行
                this.wait();
            }
            ret = data[head];
            head++;
            if (head >= data.length) {
                head = 0;
            }
            size--;

            this.notify();
        }
        return ret;
    }
}



public class Demo30 {
    public static void main(String[] args) {

    }
}
